package com.fas.hehe.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import org.apache.commons.collections.CollectionUtils;

import com.fas.core.BaseService;
import com.fas.core.constant.Constants;
import com.fas.core.constant.OperateType;
import com.fas.core.plugin.jfinal.kit.ModelKit;
import com.fas.core.plugin.treeview.TreeNode;
import com.fas.hehe.system.model.Organization;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class OrganizationService extends BaseService {

	/**
	 * 根据组织机构ID，查询组织机构对象
	 * @param orgId
	 * 				组织机构编码 
	 * @return
	 */
	public Organization findOrganizationById(Long orgId){
		return Organization.dao.findById(orgId);
	}
	
	/**
	 * 根据组织机构ID，查询组织下直属子节点
	 * @param orgId
	 * 				组织机构编码 
	 * @return
	 */
	public List<Organization> findSubOrganizationById(Long orgId){
		String sql = "select * from sys_organization where parent_id = ? order by priority asc";
		return Organization.dao.find(sql, orgId);
	}
	
	/**
	 * 一次性加载当前组织机构下面所有子机构，构建treeview插件树形结构对象列表
	 * @return
	 */
	public 	List<TreeNode> loadTreeviewOnceTime() {
		Long orgid = 1l;
		String sql = "select * from sys_organization where FIND_IN_SET(id, queryChildrenOrganization(?)) order by priority asc";
		List<Organization> list = Organization.dao.find(sql, orgid); // 后台根据父节点查询出的数据列表
		HashMap<Long, Organization> orgMap = new HashMap<Long, Organization>();
		TreeMap<Long, List<Organization>> subOrgMap = new TreeMap<Long, List<Organization>>();
		for (Organization org : list) {
			Long orgId = org.getLong("id");
			Long parentId = org.getLong("parent_id");

			if (orgId != orgid) {
				List<Organization> subList = subOrgMap.get(parentId);
				if (subList == null)
					subList = new ArrayList<Organization>();
				subList.add(org);
				subOrgMap.put(parentId, subList);
			}
			orgMap.put(orgId, org);
		}

		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		TreeNode rootNode = buildTreeNode(orgid, subOrgMap, orgMap);
		nodeList.add(rootNode);
		return nodeList;
	}
	/**
	 * 递归构建树treeview插件形对象
	 * 
	 * @param parentId
	 * 			当前节点ID
	 * @param subOrgMap
	 * 				{key: 组织机构编码Long,VALUE: 子节点列表List}
	 * @param orgMap
	 * 				{key: 组织机构编码Long,VALUE: 组织机构对象}
	 * @return
	 */
	private TreeNode buildTreeNode(Long parentId,
			TreeMap<Long, List<Organization>> subOrgMap,
			HashMap<Long, Organization> orgMap) {
		List<Organization> subList = subOrgMap.get(parentId);
		TreeNode node = new TreeNode();

		Organization curOrg = orgMap.get(parentId);
		int orgType = curOrg.getInt("org_type");
		String iconClass = "ace-icon fa fa-leaf blue ";
		if (orgType == 1) {
			iconClass = "ace-icon fa fa-institution red2";
		} else if (orgType == 2) {
			iconClass = "ace-icon fa fa-sitemap green";
		} else if (orgType == 3) {
			iconClass = "ace-icon fa fa-users blue";
		} else if (orgType == 4) {
			iconClass = "ace-icon fa fa-user orange";
		}
		String orgName = curOrg.getStr("name");
		node.setText(orgName);
		node.setIcon(iconClass);
		node.setSelected(true);
		
		List<Object> tags = new ArrayList<Object>();
		tags.add(parentId);
		node.setTags(tags);
		
		if (CollectionUtils.isNotEmpty(subList)) {
			List<TreeNode> childrenNodes = new ArrayList<TreeNode>();
			for (Organization subOrg : subList) {
				Long subOrgId = subOrg.getLong("id");
				TreeNode e = this.buildTreeNode(subOrgId, subOrgMap, orgMap);
				childrenNodes.add(e);
			}
			node.setNodes(childrenNodes);
		}
		return node;
	}
	
	/**
	 * 修改组织机构显示顺序
	 * 		
	 * @param parentId
	 * 				需要修改机构的父机构组织ID
	 * @param type
	 * 				up : 显示顺序上移一位 ,down:显示顺序下移一位
	 * @param priority
	 * 				当前需要进行修改机构的显示当前顺序
	 * @return
	 */
	@Before(Tx.class)
	public boolean changeOrganizationPriority(Long parentId, String type,int priority){
		int otherPriority = 0;
		if("up".equals(type)){
			otherPriority = priority - 1;
		}else{
			otherPriority = priority +1;
		}
		String sql = "select * from sys_organization where parent_id = ? and priority = ?";
		Organization curOrg  = Organization.dao.findFirst(sql,parentId,priority);
		Organization otherOrg  = Organization.dao.findFirst(sql, parentId,otherPriority);
		if(curOrg != null){
			curOrg.set("priority", otherPriority);
			curOrg.update();
		}
		if(otherOrg != null){
			otherOrg.set("priority", priority);
			otherOrg.update();
		}
		return true;
	}
	
	/**
	 * 删除组织机构（逻辑删除）
	 * @param orgId
	 * 			组织机构ID 
	 * @return
	 */
	public boolean deleteOrganization(Long orgId){
		Organization oldOrg = Organization.dao.findById(orgId);
		Organization newOrg = new Organization();
		ModelKit.clone(oldOrg, newOrg);
		
		oldOrg.set("available", Constants.STATUS_UNAVAILABLE);
		oldOrg.update();
		this.saveOperateLog(OperateType.UPDATE, newOrg, oldOrg, this.getLoginUser());
		return true;
	}
	
	/**
	 * 组织机构删除检查
	 * 			1、判断是否有状态为“可用”的子机构
	 * 			2、判断是否有状态为“可用”角色关联当前组织机构
	 * 			3、判断是否有状态为“可用”用户关联当前组织机构
	 * @param orgId
	 * 			组织机构ID
	 * @return  BOOLEAN  
	 * 			{true: 允许删除, false:不允许删除}
	 */
	public boolean deleteOrganizationCheck(Long orgId){
		boolean allowDelete = true;
		Long relationNum = 0l;
		String sqlOrg = "select count(1) as num from sys_organization where parent_id = ? and available = ?";
		Record rd1 = Db.findFirst(sqlOrg, orgId , Constants.STATUS_AVAILABLE);
		relationNum = rd1.getLong("num");
		
		if(relationNum > 0)
			return false;
		
		String sqlRole = "select count(1)  as num from sys_role where organization_id = ? and available = ?";
		Record rd2 = Db.findFirst(sqlRole, orgId , Constants.STATUS_AVAILABLE);
		relationNum = rd2.getLong("num");
		if(relationNum > 0)
			return false;
		
		String sqlUser = "select count(1)  as num from sys_user where organization_id = ? and available = ?";
		Record rd3 = Db.findFirst(sqlUser, orgId , Constants.STATUS_AVAILABLE);
		relationNum = rd3.getLong("num");
		if(relationNum > 0)
			return false;
		
		return allowDelete;
	}
}
